public class Solution {
    public int minFallingPathSum(int[][] matrix) {
        int m = matrix.length;//行数
        int n = matrix[0].length;//列数

        int ret = Integer.MAX_VALUE;

        int[][] dp = new int[m + 1][n + 2];

        //初始化
        //第一行全为0，最左边和最右边一列为Integer.MAX_VALUE
        for (int i = 1; i < m + 1; i++) {
            dp[i][0] = Integer.MAX_VALUE;
            dp[i][n + 1] = Integer.MAX_VALUE;
        }

        for (int i = 1; i < m + 1; i++) {
            for (int j = 1; j < n + 1; j++) {
                dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i - 1][j]), dp[i - 1][j + 1]) + matrix[i - 1][j - 1];
            }
        }

        for (int i = 1; i < n + 1; i++) {
            ret = Math.min(ret, dp[m][i]);
        }
        return ret;
    }
}
